<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-24 5:40 下午
 *
 */

namespace app\admin\controller;


use app\common\controller\AdminBaseController;
use app\common\model\tang\CostRule;
use app\common\model\tang\CostType;
use app\common\model\tang\Feedback as FeedbackModel;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\SubjectList;
use think\facade\Db;
use think\facade\Log ;

class Life  extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new \app\common\model\tang\Cost();
    }

    public function index()
    {
        if (IS_AJAX){
            $where = [
                'type'   => 2 ,
                'cost_type_id'    =>    [1, 2 ,5]
            ];
            return $this->model->getAdminPageData($this->param, 'id desc',$where,[]);
        }
        $merchant_list =\app\common\model\tang\Merchant::field('id,merchant_sn,name,company,username,code')->select();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }

    public function getCostType()
    {
        $param = $this->request->param();
        $cost_type    = intval($param['cost_type']);  //  缴费类型  1 电费  5 水费
        $merchant_id  = intval($param['merchant_id']); //  商户ID
        $number       = intval($param['number']);  //  购买数量
        $service_charge_rate = $param['service_charge_rate'];  //  手续费  %
        $cost_type_list = (new CostType())->where('pid','=',$cost_type)->field('id,type,cost_name,is_carry_down,cost_sn,tax_sn,tax_rate,tax,cost_money,th_money')->select()->toArray();
        $merchant = (new MerchantModel())->find($merchant_id);

        if($cost_type == 1){
            if($number>$merchant->number){
                return self::ajaxResult([],0,1,'商户一次最多购买'.$merchant->number.'度电');
            }
        }

        if(empty($merchant)){
            return self::ajaxResult([],0,1,'商户不存在');
        }
        if($number<=0){
            return self::ajaxResult([],0,1,'购买数量不合法');
        }
        if (empty($cost_type)){
            return self::ajaxResult([],0,1,'缴费类型不存在');
        }
        $return = [] ;
        if(!empty($cost_type_list)){
             $k = 0 ;
             $data = [] ;
             $unitprice = 0 ;
             foreach ($cost_type_list as  $v){
                 $k++ ;
                 $TaxMoneyArr = [] ;
                 if($cost_type ==1){ //  水费
                     $unit_price = $v['cost_money'] ;
                 }else{
                     if($merchant['electricity_type']==1){
                         $unit_price = $v['cost_money'] ;
                     }else{
                         $unit_price = $v['th_money'] ;
                     }
                 }
                 if($v['is_carry_down']==1){  // 转结存
                     $TaxMoneyArr = [
                         'tax_money' => 0, // 税率金额
                         'money'     => $unit_price * $number , // 收入金额
                         'z_money'   => $unit_price * $number,  // 总金额
                     ] ;
                 }else{
                     if($v['tax']==1){
                         $TaxMoneyArr = TaxMoney($unit_price,$number,$v['tax_rate']);
                     }else{
                         $TaxMoneyArr = [
                             'tax_money' => 0, // 税率金额
                             'money'     => $unit_price * $number , // 收入金额
                             'z_money'   => $unit_price * $number,  // 总金额
                         ] ;
                     }
                 }


                 $unitprice+=$unit_price ;
                 $data[] = [
                     'id'        => $v['id'],
                     'cost_name' => $v['cost_name'],
                     'type'      => $v['type'],
                     'cost_sn'   => $v['cost_sn'], // 收费科目
                     'tax_sn'    => $v['tax_sn'],  // 税率科目
                     'unitprice' => $unit_price,
                     'tax_rate'  => $v['tax_rate'],  // 税率
                     'tax_money' => $TaxMoneyArr['tax_money'], // 税率金额
                     'money'     => round($TaxMoneyArr['money'],2), // 收入金额
                     'z_money'   => round($TaxMoneyArr['money']+$TaxMoneyArr['tax_money'],2),  // 总金额
                     'is_carry_down'        => $v['is_carry_down'] // 是否转结存
                 ];
             }
            $reality_money = $unitprice * $number ;
            if($service_charge_rate>0){
                  $service_charge_money = round($reality_money * $service_charge_rate,2);
                  if($service_charge_money>0){
                      $data[$k] = [
                          'id'            => 0,
                          'cost_name'     => '手续费',
                          'type'          => '2',
                          'cost_sn'       =>  '',
                          'tax_sn'        =>  '',
                          'unitprice'     => 0,
                          'tax_rate'      => 0,  // 税率
                          'tax_money'     => 0, // 税率金额
                          'money'         => $service_charge_money, // 收入金额
                          'z_money'       => $service_charge_money,  // 总金额
                          'is_carry_down' => 0 // 是否转结存
                      ];
                  }
            }
            $service_charge_money = !empty($service_charge_money) ? $service_charge_money:0 ;
            $z_reality_money = round($service_charge_money + $reality_money ,2);
            $return = [
                'data'     => $data,
                'service_charge_money'  => $service_charge_money,
                'z_money'  => $z_reality_money
            ];
        }
        return self::ajaxResult($return,0,0,'success');
    }


    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:人工缴费
     */
    public function adminAdd()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            if (empty($data['datas'])){
                return parent::JsonReturn('缴费项不存在', 0);
            }
            Db::startTrans();
            try {
                $model =  new \app\common\model\tang\Cost();
                unset($data['__token__']);
                unset($data['date']);
                unset($data['file']);
                $data['number'] = intval($data['number']);  // 购买数量
                $unit_price = 0 ;
                $z_money = 0 ;
                $amount = 0 ;
                foreach ($data['datas'] as $v){
                    $unit_price += $v['unitprice'] ;
                    $z_money += $v['z_money'] ;
                    if($v['id']>0){
                        $amount += $v['z_money'] ;
                    }
                }
                if( (int)$z_money != (int)$data['real_amount']){
                    return parent::JsonReturn('订单价格错误', 0);
                }
                if(empty($data['b_start_time'])){
                    unset($data['b_start_time']);
                }
                if(empty($data['b_end_time'])){
                    unset($data['b_end_time']);
                }
                $data['amount'] = intval($amount * 100);
                $data['service_charge'] = intval($data['service_charge'] * 100);
                $data['unit_price'] = $unit_price ; // 单价
                $data['real_amount'] =intval($data['real_amount'] * 100);
                $data['other_certificate'] = $data['description'];
                $data['add_user'] = static::$admin_info['nickname'];
                $data['order_sn'] = OrderSn();
                $data['pay_time'] = date('Y-m-d H:i:s',time());
                $model->save($data);
                $arr = [];
                foreach ($data['datas'] as $key=>$value){
                    $arr[$key]['name'] = $value['cost_name'];
                    $arr[$key]['type'] = $value['type'];
                    $arr[$key]['unitprice'] = $value['unitprice'];
                    $arr[$key]['is_carry_down'] = $value['is_carry_down'];
                    $arr[$key]['money'] = $value['money'];
                    $arr[$key]['z_money'] = $value['z_money'];
                    $arr[$key]['cost_sn'] = $value['cost_sn'];
                    $arr[$key]['tax_sn'] = $value['tax_sn'];
                    $arr[$key]['tax_money'] = $value['tax_money'];
                    $arr[$key]['cost_type_id'] = $value['id'];
                    $arr[$key]['tax_rate'] = $value['tax_rate'];
                    $arr[$key]['pid'] = $model->id;
                    $arr[$key]['create_time'] = time();
                }
                (new CostRule())->insertAll($arr);
                $merchant  = (new MerchantModel())->find($data['merchant_id']);
                $user_info = empty($merchant['openid'])?$merchant['mobile']:$merchant['openid'] ;
                $socket = new  \app\common\controller\Socket();
                $result = $socket->connSocket($merchant['room_id'],$data['cost_type_id'],$data['number'],$amount,$data['order_sn'],$user_info);
                Log::record('-----------data------------------');
                Log::record(json_encode($result));
                Db::commit();
                return self::JsonReturn("添加成功");
            }catch (\Exception $exception){
                Db::rollback();
                return self::JsonReturn($exception->getMessage(),0);
            }
        }
        $merchant_list = (new MerchantModel())->where('status' ,'<>',-1)->field('id,merchant_sn,name,company')->select();
        $cost_type_list = (new CostType())
            ->where('type','=',2)
            ->where('id','in',['1','5'])
            ->where('pid','=',0)
            ->field('id,cost_name')->select();
        $pay_type = (new SubjectList())->where('type','=',1)->field('id,name')->select();
        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id);
        //所属部门
        $department_list = SubjectList::where('type','=',2)->field('id,name')->select();
        //获取菜单列表
        $this->assign(compact("info", "id","merchant_list","cost_type_list","department_list","pay_type"));
        return $this->fetch();
    }

    public function ServiceCharge()
    {
        $id = $this->request->param("id/d");//父id
        if (empty($id)){
            return self::ajaxResult([],0,1,'fail');
        }
        $service_charge = (\app\common\model\tang\SubjectList::where(['id'=>$id])->value('rate'))/100;
        return self::ajaxResult(['service_charge'=>$service_charge],0,0,'success');
    }

    public function detail()
    {
        $id = $this->request->param("id/d");//父id
        $info = $this->model->with(['costRule','merchants','costType'])->find($id);
        $info->time = date('Y-m-d H:i:s',$info->create_time);
        switch ($info->is_admin_create){
            case 0 :
                $info->is_user = '自主缴费';
                $info->fees_user = $info->merchant->name;
                break ;
            case 1 :
                $info->is_user = '后台缴费';
                $info->fees_user = $info->add_user;
                break ;
        }
        if(empty($info->add_user)){
            $info->add_user = $info->merchant->name;
        }
        switch ($info->pay_status){
            case -1 :
                $info->pay_status_name = '退费';
                break ;
            case 0 :
                $info->pay_status_name = '未支付';
                break ;
            case 1 :
                $info->pay_status_name = '已支付';
                break ;
        }
        $Subjectinfo = (new SubjectList())->where('id','=',$info->subject_id)->field('name')->find();
        $info->subject_id = $Subjectinfo['name'] ;
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }

    public function invoice()
    {
        $param = $this->request->param();
        $id   = intval($param['id']);
        $model =  new \app\common\model\tang\Cost();
        $cost = $model->find($id);
        if(empty($cost)){
            return self::ajaxResult([],0,1,'不存在的订单');
        }
        $invoice = empty($cost->invoice)?1:0;
        $update = $model->update(['invoice'=>$invoice],['id'=>$id]);
        if($update){
            return self::ajaxResult([],0,0,'修改成功');
        }else{
            return self::ajaxResult([],0,1,'修改失败');
        }

    }
}